package com.example.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.User;
import com.example.result.JsonResult;
import com.example.untils.RedisContent;
import com.example.service.UserService;
import com.example.untils.MailUntils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {   //用户表
    @Autowired
    private UserService userService;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //获取验证码
    @GetMapping("/gainVerCode")
    public JsonResult gainVerCode(String email){
        String sb = RandomUtil.randomString(4);
        javaMailSender.send(MailUntils.sendMail(email,sb));

        //redis存储
        stringRedisTemplate.opsForValue().set(RedisContent.LOGIN_CODE_KEY+email,sb);  //5分钟
        stringRedisTemplate.expire(RedisContent.LOGIN_CODE_KEY+email,RedisContent.LOGIN_CODE_TTL,TimeUnit.MINUTES);

        return new JsonResult(1,"请注意接收!");
    }
    //用户邮箱登录
    @PostMapping("/login")
    public JsonResult login(String email,String code,HttpSession session){
        log.info(email+"....."+code);
        //获取redis中的验证码
        String sb=stringRedisTemplate.opsForValue().get(RedisContent.LOGIN_CODE_KEY+email);
        log.info("验证码："+sb);
        if(sb==null||!sb.equalsIgnoreCase(code)){    //忽略大小写
            throw new RuntimeException("验证码错误");
        }
        //删除校验码
        stringRedisTemplate.delete(RedisContent.LOGIN_CODE_KEY+email);

        //查询数据，如果没有就添加
        LambdaQueryWrapper<User> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(User::getEmail,email);
        User one = userService.getOne(queryWrapper1);
        if(one==null){
            //新用户添加
            User user=new User();
            user.setName("新用户"+RandomUtil.randomString(6));
            user.setEmail(email);
            user.setAvatar("cfb620cf-585f-4a4e-ab6a-652c49c72694.jpg");
            userService.save(user);
            one=user;
        }
        session.setAttribute("user",one);
        return new JsonResult(1,"登录成功");
    }
    //用户退出
    @GetMapping("/loginout")
    public JsonResult loginout(HttpSession session){
        session.removeAttribute("user");
        return new JsonResult(1,"");
    }
    //获取当前用户信息
    @GetMapping("/getUser")
    public JsonResult getUser(HttpSession session){
        User user=(User) session.getAttribute("user");
        return new JsonResult(1,"",user);
    }
}
